package com.wispx.shortlink.admin.common.biz.user;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSON;
import com.wispx.shortlink.admin.common.convention.exception.ClientException;
import com.wispx.shortlink.admin.common.convention.result.Results;
import com.wispx.shortlink.admin.configuration.UserFlowRiskControlConfiguration;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

/**
 * 用户流量风控过滤器
 */
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;

    private static final String USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 加载lua脚本
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH)));
        redisScript.setResultType(Long.class);

        String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");

        // 执行lua脚本
        Long result = null;
        try {
            result = stringRedisTemplate.execute(redisScript, ListUtil.toList(username), userFlowRiskControlConfiguration.getTimeWindow());
        }catch (Exception ex){
            throw new ServletException("执行lua脚本出错");
        }

        // 判断是否放行
        if(result == null || result > userFlowRiskControlConfiguration.getMaxAccessCount()){
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException("访问过于频繁,请稍后再试"))));
            return;
        }

        try{
            chain.doFilter(request,response);
        }catch (Exception ignored){

        }

    }

    private void returnJson(HttpServletResponse response, String json) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter out = response.getWriter()){
            out.print(json);
        }
    }

}
